/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import $ from 'jquery';
import { defer } from 'lodash';

// Renders
import SaikuTableRenderer from '../../../renders/SaikuTableRenderer';

// Utils
import { Settings } from '../../../utils';

// Styles
import './Table.css';

class Table extends Component {
  constructor(props) {
    super(props);

    this.saikuTableRenderer = new SaikuTableRenderer();
  }

  componentDidMount() {
    const { queryResultset } = this.props.queryResultset;

    // Render the table without blocking the UI thread
    defer(this.processData, queryResultset);
  }

  shouldComponentUpdate(nextProps, nextState) {
    const queryResultsetProps = this.props.queryResultset;
    const queryResultsetNextProps = nextProps.queryResultset;

    return (
      queryResultsetProps.queryResultset.width !==
        queryResultsetNextProps.queryResultset.width ||
      queryResultsetProps.queryResultset.height !==
        queryResultsetNextProps.queryResultset.height ||
      queryResultsetProps.queryResultset.runtime !==
        queryResultsetNextProps.queryResultset.runtime
    );
  }

  componentWillUpdate(nextProps, nextState) {
    const { queryResultset } = nextProps.queryResultset;

    // Render the table without blocking the UI thread
    defer(this.processData, queryResultset);
  }

  componentWillUnmount() {
    this.$rootNode.empty();
  }

  processData = data => {
    this.$rootNode = $(this.rootNode);

    this.saikuTableRenderer.render(data, {
      htmlObject: this.$rootNode,
      batch: Settings.TABLE_LAZY,
      batchSize: Settings.TABLE_LAZY_SIZE,
      batchIntervalSize: Settings.TABLE_LAZY_LOAD_ITEMS,
      batchIntervalTime: Settings.TABLE_LAZY_LOAD_TIME
    });
  };

  render() {
    return (
      <table
        ref={node => (this.rootNode = node)}
        className="sku-table-wrapper"
      />
    );
  }
}

Table.propTypes = {
  queryResultset: PropTypes.object.isRequired
};

export default Table;
